package com.wobito.common.utils;


import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;

/**
 * @Author: lambyang
 * @CreateTime: 2024-09-29
 * @Description:
 * @Version: 1.0
 */
public class MultipartFileToBase64Util {

    /**
     * 将MultipartFile转换为Base64编码的字符串
     *
     * @param file MultipartFile对象
     * @return Base64编码的字符串
     * @throws IOException 如果读取文件时发生错误
     */
    public static String multipartFileToBase64(MultipartFile file)  {
        byte[] bytes = null; // 直接从MultipartFile获取字节数组
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (bytes == null || bytes.length == 0) {
           throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }
        return Base64.getEncoder().encodeToString(bytes);
    }

}
